<template>
  <div class="role-list">
    <el-card class="role-card">
      <template #header>
        <div class="card-header">
          <span>角色管理</span>
          <el-button type="primary" @click="handleAdd">添加角色</el-button>
        </div>
      </template>

      <el-table
        :data="roleList"
        v-loading="loading"
        style="width: 100%"
        row-key="id"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="角色名称" width="150" />
        <el-table-column prop="code" label="角色代码" width="150" />
        <el-table-column prop="description" label="描述" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleView(scope.row)">查看</el-button>
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button
              size="small"
              :type="scope.row.status === 1 ? 'warning' : 'success'"
              @click="handleToggleStatus(scope.row)"
              :disabled="scope.row.id === 1"
            >
              {{ scope.row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
              :disabled="scope.row.id === 1"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑角色对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        :rules="roleRules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" :maxlength="50" show-word-limit :disabled="isEdit && currentRoleId === 1" />
        </el-form-item>
        <el-form-item label="角色代码" prop="code">
          <el-input v-model="roleForm.code" :maxlength="50" show-word-limit :disabled="isEdit" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="roleForm.description" type="textarea" :maxlength="200" show-word-limit :disabled="isEdit && currentRoleId === 1" />
        </el-form-item>
        <el-form-item v-if="isEdit && currentRoleId !== 1" label="状态" prop="status">
          <el-switch
            v-model="roleForm.status"
            :active-value="1"
            :inactive-value="0"
            active-text="正常"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave" :loading="saveLoading">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 权限分配对话框 -->
    <el-dialog
      v-model="permissionDialogVisible"
      title="权限分配"
      width="800px"
      @close="handlePermissionDialogClose"
    >
      <el-tree
        ref="permissionTreeRef"
        :data="permissionTreeData"
        show-checkbox
        node-key="id"
        :props="{
          children: 'children',
          label: 'name'
        }"
        :default-checked-keys="defaultCheckedPermissions"
        :default-expanded-keys="defaultExpandedPermissions"
      />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="permissionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSavePermissions" :loading="permissionSaveLoading">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { Role, CreateRoleRequest, UpdateRoleRequest } from '@/types/api/role'
import type { Permission } from '@/types/api/permission'
import { roleApi } from '@/api/modules/role'
import { permissionApi } from '@/api/modules/permission'
import { formUtils } from '@/utils'

// 表格相关
const loading = ref(false)
const roleList = ref<Role[]>([])

// 权限相关
const permissionList = ref<Permission[]>([])
const permissionTreeData = ref<any[]>([])
const defaultCheckedPermissions = ref<number[]>([])
const defaultExpandedPermissions = ref<number[]>([])

// 对话框相关
const dialogVisible = ref(false)
const permissionDialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)
const saveLoading = ref(false)
const permissionSaveLoading = ref(false)
const roleFormRef = ref()
const permissionTreeRef = ref()
const currentRoleId = ref(0)

// 表单数据
const roleForm = reactive({
  name: '',
  code: '',
  description: '',
  status: 1
})

// 表单验证规则
const roleRules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { max: 50, message: '角色名称长度不能超过50个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入角色代码', trigger: 'blur' },
    { max: 50, message: '角色代码长度不能超过50个字符', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '描述长度不能超过200个字符', trigger: 'blur' }
  ]
}

// 获取角色列表
const getRoleList = async () => {
  loading.value = true
  try {
    const response = await roleApi.getRoleList()
    roleList.value = response.data.data
  } catch (error) {
    ElMessage.error('获取角色列表失败')
  } finally {
    loading.value = false
  }
}

// 获取权限列表并构建树形结构
const getPermissionList = async () => {
  try {
    const response = await permissionApi.getPermissionList()
    permissionList.value = response.data.data

    // 构建权限树形结构
    const resourceMap: Record<string, any> = {}
    permissionList.value.forEach(permission => {
      if (!resourceMap[permission.resource]) {
        resourceMap[permission.resource] = {
          id: `resource_${permission.resource}`,
          name: getResourceName(permission.resource),
          children: []
        }
      }
      resourceMap[permission.resource].children.push({
        id: permission.id,
        name: `${getActionName(permission.action)}-${permission.name}`,
        permission: permission
      })
    })

    permissionTreeData.value = Object.values(resourceMap)
  } catch (error) {
    ElMessage.error('获取权限列表失败')
  }
}

// 获取资源名称
const getResourceName = (resource: string) => {
  const resourceMap: Record<string, string> = {
    'user': '用户管理',
    'role': '角色管理',
    'permission': '权限管理',
    'member': '会员管理',
    'course': '课程管理',
    'coach': '教练管理',
    'plan': '健身计划',
    'booking': '预约管理',
    'card': '会员卡管理',
    'checkin': '签到管理',
    'statistics': '统计分析',
    'notification': '通知管理',
    'review': '评价反馈',
    'file': '文件管理',
    'system': '系统管理'
  }
  return resourceMap[resource] || resource
}

// 获取操作名称
const getActionName = (action: string) => {
  const actionMap: Record<string, string> = {
    'create': '创建',
    'read': '查看',
    'update': '更新',
    'delete': '删除'
  }
  return actionMap[action] || action
}

// 添加角色
const handleAdd = () => {
  dialogTitle.value = '添加角色'
  isEdit.value = false
  dialogVisible.value = true
  // 重置表单
  Object.assign(roleForm, {
    name: '',
    code: '',
    description: '',
    status: 1
  })
}

// 编辑角色
const handleEdit = (row: Role) => {
  dialogTitle.value = '编辑角色'
  isEdit.value = true
  dialogVisible.value = true
  currentRoleId.value = row.id
  // 填充表单数据
  Object.assign(roleForm, {
    name: row.name,
    code: row.code,
    description: row.description,
    status: row.status
  })
}

// 查看角色详情
const handleView = (row: Role) => {
  dialogTitle.value = '角色详情'
  isEdit.value = false
  dialogVisible.value = true
  currentRoleId.value = row.id
  // 填充表单数据
  Object.assign(roleForm, {
    name: row.name,
    code: row.code,
    description: row.description,
    status: row.status
  })
}

// 启用/禁用角色
const handleToggleStatus = async (row: Role) => {
  if (row.id === 1) {
    ElMessage.warning('不能禁用超级管理员角色')
    return
  }

  try {
    const status = row.status === 1 ? 0 : 1
    await roleApi.updateRole(row.id, {
      status: status
    })
    ElMessage.success(`${status === 1 ? '启用' : '禁用'}成功`)
    await getRoleList()
  } catch (error) {
    ElMessage.error(`${row.status === 1 ? '禁用' : '启用'}失败`)
  }
}

// 删除角色
const handleDelete = (row: Role) => {
  if (row.id === 1) {
    ElMessage.warning('不能删除超级管理员角色')
    return
  }

  formUtils.handleDeleteConfirm(`角色 "${row.name}"`, async () => {
    await roleApi.deleteRole(row.id)
    getRoleList()
  }, {
    successMessage: '删除成功',
    errorMessage: '删除失败'
  })
}

// 权限分配
const handlePermissionAssign = async (row: Role) => {
  currentRoleId.value = row.id
  permissionDialogVisible.value = true

  try {
    // 获取角色的权限
    const rolePermissionsResponse = await roleApi.getRolePermissions(row.id)
    const rolePermissions = rolePermissionsResponse.data.data
    defaultCheckedPermissions.value = rolePermissions.map(p => p.id)

    // 默认展开所有资源节点
    defaultExpandedPermissions.value = permissionTreeData.value.map(node => node.id)
  } catch (error) {
    ElMessage.error('获取角色权限失败')
  }
}

// 保存权限分配
const handleSavePermissions = async () => {
  if (!permissionTreeRef.value) return

  permissionSaveLoading.value = true
  try {
    const checkedKeys = permissionTreeRef.value.getCheckedKeys()
    const halfCheckedKeys = permissionTreeRef.value.getHalfCheckedKeys()
    const allCheckedKeys = [...checkedKeys, ...halfCheckedKeys]

    await roleApi.assignPermissionsToRole(currentRoleId.value, {
      permissionIds: allCheckedKeys.filter(key => typeof key === 'number')
    })
    ElMessage.success('权限分配成功')
    permissionDialogVisible.value = false
  } catch (error) {
    ElMessage.error('权限分配失败')
  } finally {
    permissionSaveLoading.value = false
  }
}

// 保存角色信息
const handleSave = async () => {
  if (!roleFormRef.value) return

  await roleFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      saveLoading.value = true
      try {
        if (isEdit.value) {
          // 编辑角色
          const updateData: UpdateRoleRequest = {}
          if (currentRoleId.value !== 1) {
            updateData.name = roleForm.name
            updateData.description = roleForm.description
            updateData.status = roleForm.status
          } else {
            updateData.name = roleForm.name
            updateData.description = roleForm.description
          }
          await roleApi.updateRole(currentRoleId.value, updateData)
          ElMessage.success('更新成功')
        } else {
          // 添加角色
          const createData: CreateRoleRequest = {
            name: roleForm.name,
            code: roleForm.code,
            description: roleForm.description
          }
          await roleApi.createRole(createData)
          ElMessage.success('添加成功')
        }
        dialogVisible.value = false
        await getRoleList()
      } catch (error: any) {
        ElMessage.error(error.message || (isEdit.value ? '更新失败' : '添加失败'))
      } finally {
        saveLoading.value = false
      }
    }
  })
}

// 对话框关闭
const handleDialogClose = () => {
  formUtils.resetForm(roleFormRef.value, roleForm, {
    name: '',
    code: '',
    description: '',
    status: 1
  })
}

// 权限对话框关闭
const handlePermissionDialogClose = () => {
  defaultCheckedPermissions.value = []
  defaultExpandedPermissions.value = []
}

// 初始化
onMounted(() => {
  getRoleList()
  getPermissionList()
})
</script>

<style scoped lang="scss">
.role-list {
  .role-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
}
</style>
